<template>
  <div class="create-component-list">
    <div class="component-item" v-for="(item, index) in list" :key="index" @click="onItemClick(item)">
      <l-text v-bind="item"></l-text>
    </div>
  </div>
  <styled-uploaders @success="onImageUploaded"></styled-uploaders>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import LText from "./LText.vue";
import { ComponentData } from "@/store/editor";
import { v4 as uuidv4 } from "uuid";
import { imageDefaultProps, TextComponentProps } from "@/defaultProps";
import StyledUploaders from "./StyledUploaders.vue";
import { UploadResp } from "@/extraType";
import { message } from "ant-design-vue";
import { getImageDimensions } from "@/helper";

export default defineComponent({
  props: {
    list: {
      type: Array as any,
      required: true,
    },
  },
  name: "components-list",
  components: {
    StyledUploaders,
    LText,
  },
  emits: ["on-item-click"],
  setup(props, context) {
    const onItemClick = (props: TextComponentProps) => {
      const componetData: ComponentData = {
        name: "l-text",
        id: uuidv4(),
        props,
      };

      context.emit("on-item-click", componetData);
    };

    const onImageUploaded = (resp: UploadResp) => {
      const componentData: ComponentData = {
        name: "l-image",
        id: uuidv4(),
        props: {
          ...imageDefaultProps,
        },
      };
      message.success("上传成功");
      componentData.props.src = resp.data.url;
      getImageDimensions(resp.data.url).then(({ width }) => {
        const maxWidth = 373;
        componentData.props.width = width > maxWidth ? maxWidth : width;
        context.emit("on-item-click", componentData);
      });
    };

    return {
      onItemClick,
      onImageUploaded,
    };
  },
});
</script>

<style>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}
.component-item > {
  position: static !important;
}
</style>
